<?php

require_once 'constants.php';

class Buffalo_Cart {

    static function add_to_cart($pid) {
        if (!is_array($_SESSION[CART])) {
            $_SESSION[CART] = array();
        }

        if (!self::check_and_update($pid)) {
            array_push($_SESSION[CART], array('pid' => $pid, 'quantity' => 1));
        }
    }

    static function get_total_quantity() {
        $quantity = 0;

        if (is_array($_SESSION[CART])) {
            foreach ($_SESSION[CART] as $item) {
                $quantity += $item['quantity'];
            }
        }

        return $quantity;
    }

    public static function get_subtotal() {
        $subtotal = 0;

        if (is_array($_SESSION[CART])) {
            foreach ($_SESSION[CART] as $item) {
                $price = get_post_meta($item['pid'], PRICE_META_KEY, true);
                $subtotal += $price * $item['quantity'];
            }
        }

        return $subtotal;
    }

    public static function get_products() {
        $cart = array();

        if (is_array($_SESSION[CART])) {
            foreach ($_SESSION[CART] as $item) {
                $product = array();
                $p = get_post($item['pid']);
                $product['pid'] = $item['pid'];
                $product['name'] = $p->post_title;
                $product['price'] = get_post_meta($item['pid'], PRICE_META_KEY, true);
                $product['quantity'] = $item['quantity'];
                $product['total_price'] = $item['quantity'] * $product['price'];
                array_push($cart, $product);
            }
        }

        return $cart;
    }

    public static function check_and_update($pid, $quantity = 1, $overlay=false) {
        $count = count($_SESSION[CART]);
        for ($i = 0; $i < $count; $i++) {
            if ($pid == $_SESSION[CART][$i]['pid']) {
                if ($overlay) {
                    $_SESSION[CART][$i]['quantity'] = $quantity;
                } else {
                    $_SESSION[CART][$i]['quantity'] += $quantity;
                }

                return true;
            }
        }

        return false;
    }

    public static function remove_product($pid) {
        $count = count($_SESSION[CART]);
        for ($i = 0; $i < $count; $i++) {
            if ($pid == $_SESSION[CART][$i]['pid']) {
                unset($_SESSION[CART][$i]);
                break;
            }
        }
    }

}

?>
